package data_structure.mooc.uf;

/**
 * 线段树
 * 平衡二叉树
 * 树中的非叶子节点表示的是一定区间范围内元素的信息
 */
public class SegmentTree<E> {

    private E []data;

    //线段树储存数组
    private E[]tree;
    //非叶子节点储存的数据，处理的业务，通过Merger接口实现
    private Merger<E>merger;
    public SegmentTree(E []arr,Merger<E> merger){
        this.merger = merger;
        data=(E[])new Object[arr.length];
        for (int i = 0; i < arr.length; i++) {
            data[i] = arr[i];
        }
        //线段树的容量为数组长度的四倍
        tree=(E [])new Object[4*arr.length];
        buildSegmentTree(0,0,arr.length-1);
    }

    private int leftChild(int index){
        return 2*index+1;
    }
    private int rightChild(int index){
        return 2*index+2;
    }
    /**
     * 在index位置上（tree）表示范围为[l,r]的线段树
     *  tree[index]=merger.merge (tree[leftChild],tree[rightChild])
     * @param index 当前节点
     * @param l 左边界
     * @param r 右边界
     */
    public void buildSegmentTree(int index,int l,int r){

        if(l==r){
            tree[index]=data[l];
            return;
        }
        int leftChild=leftChild (index);
        int rightChild = rightChild(index);

        int mid=l+(r-l)/2;
        //开始递归
        //leftChild l l+mid
        //rightChild l+mid+1 r
        buildSegmentTree (leftChild,l,mid);
        buildSegmentTree (rightChild,mid+1,r);
        tree[index]=merger.merge (tree[leftChild],tree[rightChild]);
    }

    /**
     * 查询区间为[queryL,queryR]对应的线段树中节点的值
     */
    public E query(int queryL,int queryR){
        return query(0,0,data.length-1,queryL,queryR);
    }

    /**
     *在以treeIndex为根节点的线段树，范围为[l,r]查询[queryL,queryR]区间对应树中的节点
     */
    private E query(int treeIndex,int l,int r,int queryL,int queryR){

        //递归到底时
        if(l==queryL&&r==queryR){
            return tree[treeIndex];
        }

        //leftChild,rightChild,mid
        int leftChild=leftChild (treeIndex);
        int rightChild=rightChild(treeIndex);
        int mid=l+(r-l)/2;
        //处理三个区间
        //[l,mid],[mid+1,r],[queryL,queryR]
        //[mid+1,r]
        if(queryL>=mid+1){
            return query(rightChild,mid+1,r,queryL,queryR);
            //[]l,mid]
        }else if(queryR<=mid){
            return query(leftChild,l,mid,queryL, queryR);
        }else{
            //[l,mid],[mid+1,r]
            E leftResult=query (leftChild,l,mid,queryL,mid);
            E rightResult=query(rightChild,mid+1,r,mid+1,queryR);
            return merger.merge (leftResult, rightResult);
        }
    }

    /**
     *更新index位置的元素
     */
    public void set(int index,E e){
        if (index < 0 || index >= data.length){
            throw new IndexOutOfBoundsException("Illegal Index");
        }
        data[index]=e;
        set(0,0,data.length-1,index,e);
    }

    private void set(int treeRootIndex,int l,int r,int index,E e){

        //递归结束情况
        if(l==r){
            tree[treeRootIndex]=e;
            return;
        }

        int mid=l+(r-l)/2;
        int leftChild=leftChild (treeRootIndex);
        int rightChild=rightChild (treeRootIndex);

        if(index<=mid){
            //在左子树执行更新操作
            set(leftChild,l,mid,index,e);
        }else{
            //在右子树执行更新操作
            set(rightChild,mid+1,r,index,e);
        }
        //维护线段树的特点
        //更新index位置后的元素后，线段树的特点可能会改变
        tree[treeRootIndex]=merger.merge (tree[leftChild],tree[rightChild]);
    }
    public int getSize(){
        return data.length;
    }
    public E get(int index){

        if(index < 0 || index >= data.length){
            throw new IndexOutOfBoundsException("Illegal Index");
        }
        return data[index];
    }

    @Override
    public String toString() {

        StringBuilder sb = new StringBuilder();
        sb.append ("[");
        for(int i=0;i<tree.length;i++){
            if(tree[i]!=null){
                sb.append (tree[i]);
            }else{
                sb.append ("null");
            }
            if(i!=tree.length - 1)sb.append (",");
        }
        sb.append ("]");
        return sb.toString ();
    }

    public static void main(String[] args) {
        Integer []nums=new Integer[]{1,2,3,4,5,6,7,8,9,10};
        SegmentTree<Integer>segment=new SegmentTree<> (nums, (a,b)->a+b);
        segment.set(4,100);
        System.out.println(segment.toString ());
    }
}
